const util = require('../../utils/util')
const db = wx.cloud.database()
const sport = db.collection('sport')
const userInfo = db.collection('userInfo')
const user = db.collection('user')
const join = db.collection('join')

Page({
  data: {
    activityid: '',
    joinid: '',
    willjoinid: '',
    sport: [],
    userList: [],
    user: [],
    count: 1,
  },
  onLoad: function (options) {
    console.log(options)
    sport.doc(options._id).get({
      success: res => {
        console.log(res)
        res.data.price = util.formatTime(res.data.price)
        this.setData({
          sport: res.data,
          activityid: res.data._id
        })
      }
    })
    userInfo.where({
      _openid: options._openid
    }).get().then(res => {
      console.log(res.data)
      this.setData({
        userList: res.data
      })
    })
    user.where({
      _openid: options._openid
    }).get().then(res => {
      console.log(res.data)
      this.setData({
        user: res.data,
        joinid: res.data[0]._openid,
      })
    })
    wx.cloud.callFunction({
      name: 'getOpenId',
      success: res => {
        console.log(res.result.openId)
        this.setData({
          willjoinid: res.result.openId
        })
      }
    })
  },
  onSubmit: function () {
    join.where({
      activityid: this.data.activityid,
      joinid: this.data.willjoinid
    }).count({
      success: res => {
        console.log(res)
        this.setData({
          count: res.total
        })
        console.log(this.data.count)

        if (this.data.count != 0) {
          wx.showToast({
            title: '你已预约组队',
          })
        } else {
          join.add({
            data: {
              activityid: this.data.activityid,
              joinid: this.data.willjoinid,
              title: this.data.sport.title,
              dese: this.data.sport.dese,
              show: this.data.sport.show,
              num: this.data.sport.num,
              price: new Date(this.data.sport.price),
              local: this.data.sport.local,
              others: this.data.sport.others
            },
            success: res => {
              wx.showToast({
                title: '预约成功',
                icon: 'success',
                duration: 2000
              })
              wx.navigateTo({
                url: '../order/order?activityid=' + this.data.activityid + "&name=" + this.data.user[0].username,
              })
              console.log('新增数据成功，记录_id:', res._id)
            },
            fail: err => {
              wx.showToast({
                title: '信息发布失败',
                icon: 'none'
              })
              console.error('信息发布失败', err)
            }
          })
        }
      }
    })
  }

})